/*
 * =====================================================================================
 *
 *       Filename:  app.c
 *
 *    Description:  阻塞型字符设备驱动操作测试类
 *
 *        Version:  1.0
 *        Created:  2015年09月19日 09时44分37秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#define MEMDEV_SIZE 4096

int main(int argc, char *argv[])
{
    int fd ,ret;
    char buf[MEMDEV_SIZE];
    printf("One processes read ,Another write>>>>");
    if(-1 == (ret = fork())){
        printf("fork() error\n");
        _exit(EXIT_FAILURE);
    }else if(0 != ret){
        
        printf("This is Father proccess : %d \n",getpid());
        if(-1 == (fd=open("/dev/memdev0",O_RDWR))){
            printf("open() error");
            perror("father read proccess error \n");
            _exit(EXIT_FAILURE);
        }
        printf("Father try to read , but there is no data ,blocking...\n");
        int ret = 0 ;
        ret = read(fd,buf,20);
        printf("After child write1 , Father can read :\n");
        buf[ret] = 0;
        printf("Father read1(%d bytes):%s\n",ret ,buf);
        ret = read(fd,buf,20);
        buf[ret] = 0;
        printf("Falther read2 (%d bytes):%s\n",ret ,buf);
        printf("Father read3 , no data to read , blocking...\n");
        ret = read(fd,buf,50);
        buf[ret] = 0; 
        printf("After child write2,Father read3 (%d bytes):%s\n",ret ,buf);
        printf("Father sleep 10s ....\n\n");
        sleep(10);
        ret = read(fd,buf,20);
        printf("Father read4 (%d bytes)\n",ret);
        wait(NULL);
        close(fd); 
    }else{
        //子进程
        printf("This is child proccess : %d \n",getpid());
        if(-1 == (fd = open("/dev/memdev0",O_RDWR))){
            printf("open() error");
            perror("child read proccess error \n");
            _exit(EXIT_FAILURE);
        }
        printf("Child sleep 5s ..\n\n");
        sleep(5);
        strcpy(buf,"Here is the CHILD writing ...");
        ret = write(fd ,buf,strlen(buf));
        printf("Chld writel1 (%d byes):%s\n",strlen(buf),buf);
        sleep(5);
        printf("child sleep 10s ....");
        sleep(10);
        ret = write(fd,buf,sizeof(buf));
        printf("childe write2 (%d byes):%s\n",ret,buf);
        sleep(5);
        ret = write(fd,buf,sizeof(buf));
        printf("chile write3 (%d bytes --- buf is full)\n",ret);
        printf("Child try to write ,but there is no space ,blocking...\n");
        ret = write(fd, buf,strlen(buf));
        printf("After Father read4,child write4(%d bytes):%s\n",ret ,buf);
        close(fd);
        _exit(EXIT_SUCCESS); 
    }
    printf("Process : %d end\n",getpid());
    _exit(EXIT_SUCCESS);
}

